<template>
  <!-- 添加或修改录单记录对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body @close="cancel" close-on-press-escape>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="总部编号" prop="zbbh">
            <el-input v-model="form.zbbh" placeholder="请输入总部编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="gsmc">
            <el-input v-model="form.gsmc" placeholder="请输入公司名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="原始记录" prop="ysjl">
            <el-input v-model="form.ysjl" type="number" placeholder="请输入原始记录" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际录入" prop="sjlr">
            <el-input v-model="form.sjlr" type="number" placeholder="请输入实际录入" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="日期" prop="rq">
<!--            <el-select v-model="form.yf" style="width: 100%;" placeholder="请选择">-->
<!--              <el-option-->
<!--                v-for="item in yfList"-->
<!--                :key="item.dictValue"-->
<!--                :label="item.dictLabel"-->
<!--                :value="item.dictValue">-->
<!--              </el-option>-->
<!--            </el-select>-->
            <el-date-picker
              v-model="form.rq"
              style="width: 100%;"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属公司" prop="yf">
            <el-select v-model="form.createDeptName" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in ssgsList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="7">
          <el-form-item label="下场" prop="xc">
            <el-radio-group v-model="form.xc">
              <el-radio v-for="item in sfList" border :label="item.dictValue">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="修改" prop="xg">
            <el-radio-group v-model="form.xg">
              <el-radio v-for="item in sfList" border :label="item.dictValue">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="证书" prop="zs">
            <el-input v-model="form.zs" type="number" placeholder="请输入证书" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="附件" prop="fj">
            <el-upload
              class="upload-demo"
              :action="src"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-remove="handleRemove"
              :headers="uploadHeaders"
              multiple
              :file-list="fjList"
              :on-preview="handlePreview"
            >
              <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

<!--      <el-row>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="录单人" prop="createBy">-->
<!--            <el-input v-model="form.createBy" readonly />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="录单时间" prop="createTime">-->
<!--            <el-input v-model="form.createTime" readonly />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="bz">
            <el-input
              type="textarea"
              maxlength="1000"
              :autosize="{ minRows: 3, maxRows: 4 }"
              show-word-limit
              placeholder="请输入备注"
              v-model="form.bz">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button  v-if="ShowBtn" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addLdjl, getLdjl, updateLdjl } from '@/api/gd/ldjl'
import { allListFj, delFj, getFj } from '@/api/gd/fj'
import axios from 'axios'

export default {
  name: 'formInfo',
  props: {
    title: {
      type: String
    },
    formInfo: {
      type: Object
    },
    ShowBtn: {
      type: Boolean
    },
    open: {
      type: Boolean
    }
  },
  data() {
    return {
      sfList: [],
      form: {},
      ssgsList: [],
      yfList: [],
      buttonLoading: false,
      fjList: [],
      src: this.uploadSrc + '/gd/fj/file/upload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      // 表单校验
      rules: {
        gsmc: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        rq: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.init()
    this.getDict()
  },
  methods: {
    init() {
      getLdjl(this.formInfo.id).then(response => {
        // 处理附件数据
        if (response.data.fj !== "" && response.data.fj !== null && response.data.fj !== undefined) {
          allListFj(response.data.fj).then(res => {
            if (res !== null && res.data !== null) {
              res.forEach(item => {
                const obj = {
                  id: item.fjid,
                  name: item.fjname,
                  path: item.fjpath
                }
                this.fjList.push(obj)
              })
            }
          })
        }
        this.form = response.data;
      });
    },
    getDict() {
      // 月份
      this.getDicts("gd_yf").then(res => {
        this.yfList = res.data
      })
      // 所属公司
      this.getDicts("gd_ssgs").then(res => {
        this.ssgsList = res.data
      })
      // 是否
      this.getDicts("sys_yes_no").then(res => {
        this.sfList = res.data
      })
    },
    cancel() {
      this.fjList = []
      this.$emit("close")
    },
    // ======  上传开始  ======
    handleSuccess(response, file) {
      if (this.ShowBtn) {
        let fj = response.fj  // 上传的附件id
        let currentFj = this.form.fj
        if (currentFj != '' && currentFj !== null && currentFj !== undefined) {
          let fjArr = currentFj.split(",")
          fjArr.push(fj)
          this.form.fj = fjArr.toString()
        }else {
          this.form.fj = fj
        }
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        let than = this
        if (this.form.id !== undefined) {
          updateLdjl(this.form).then(objs => {
            getLdjl(this.form.id).then(async response => {
              than.fjList = []
              let obj = response.data
              if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                await allListFj(response.data.fj).then(res => {
                  if (res !== null && res.data !== null) {
                    res.forEach(item => {
                      const obj = {
                        id: item.fjid,
                        name: item.fjname,
                        path: item.fjpath
                      }
                      than.fjList.push(obj)
                    })
                  }
                })
              }
            })
          })
        }
      }else {
        this.fjList = []
        this.$message.error("当前是预览状态，禁止上传")
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      if (this.ShowBtn) {
        this.$modal.confirm('请确认是否删除附件名称为：'+file.name+' 的数据?').then(() => {
          let ids = fileList.filter(item => (item.id !== file.id) || (item.fjid !== file.fjid)).map(item => (item.id) || (item.fjid)).toString()
          let fjId = []
          fjId.push((file.id) || (file.fjid))
          let than = this
          delFj(fjId).then(res => {
            if (res.code === 200) {
              this.$message.success("删除成功！")
              if (ids !== '' && ids !== null) {
                this.form.fj = ids
                updateLdjl(this.form).then(objs => {
                  getLdjl(this.form.id).then(async response => {
                    than.fjList = []
                    let obj = response.data
                    if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                      await allListFj(response.data.fj).then(res => {
                        if (res !== null && res.data !== null) {
                          res.forEach(item => {
                            const obj = {
                              id: item.fjid,
                              name: item.fjname,
                              path: item.fjpath
                            }
                            than.fjList.push(obj)
                          })
                        }
                      })
                    }
                  })
                })
              }
            }
          })
        }).catch(() => {
          fileList.push(file)
        })
      }else {
        this.fjList = []
        this.$message.error("当前是预览状态，禁止删除")
      }
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.fjid || file.response.fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // ====== 文件上传结束 ======
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateLdjl(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLdjl(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
  }
}
</script>

<style scoped>

</style>
